import { Component, Input, OnInit, AfterViewInit } from '@angular/core';
import { TreeNode } from 'primeng/primeng';
import { QkPartService } from './qkpart.service';
@Component({
  selector: 'qkrole-selector',
  templateUrl: './qkrole-selector.component.html',
  styleUrls: ['./qkrole-selector.component.scss'],
  providers: [QkPartService]
})
export class QkRoleSelectorComponent implements OnInit {
  @Input() checkedParts: TreeNode[];
  checkedRoles: TreeNode[] = [];
  unitRoles: TreeNode[]  = []; //机构岗位树
  loading: boolean = true;
  suggestion: TreeNode;
  suggestions: TreeNode[]; //下拉选项

  constructor(private qkPartService: QkPartService) { }

  ngOnInit() {
    this.qkPartService.getUnitRoleTree(0, true)
      .subscribe(data => {
        this.loading = false;
        this.unitRoles = data;
        // this.checkedParts.forEach(node => {
        //   if (node['data']['type'] == '岗位') {
        //     this.recursionExpendSuggestionTreeNode(this.unitRoles, node['data']['unitCode'], node['id']);
        //   }
        // });
      });
  }

  /**岗位查找 */
  search(event) {
    if (!event.query) return;
    this.qkPartService.searchUnitRoleByName(event.query).subscribe(data => {
      data.forEach(ele => ele["roleName"] = ele["roleName"] + "(" + ele["roleId"] + ")")
      this.suggestions = data;
    });
  }

  /** 树节点展开事件 */
  unitNodeExpand(event) {
    if (event.node && event.node.children.length == 0) {
      this.qkPartService.getUnitRoleTree(event.node.id, false).subscribe(nodes => event.node.children = nodes);
    }
  }

  /**选择下拉事件 */
  selectSuggestion() {
    this.recursionExpendSuggestionTreeNode(this.unitRoles, this.suggestion["unitCode"], this.suggestion['roleId']);
  }

  /**递归展开查询的树 */
  recursionExpendSuggestionTreeNode(unitRoles: TreeNode[], roleUnitCode: string, roleId: string) {
    unitRoles.forEach(ele => {
      if (roleId == ele['id']) {
        this.checkedRoles.push(ele);
        return
      }
      if (roleUnitCode.indexOf(ele.data['code']) != -1) {
        //展开树节点
        ele.expanded = true;
        if (ele['data']['type'] == 'U') {
          if (ele.children && ele.children.length > 0) {
            this.recursionExpendSuggestionTreeNode(ele.children, roleUnitCode, roleId);
          } else {
            this.qkPartService.getUnitRoleTree(+ele["id"], false).subscribe(nodes => {
              ele.children = nodes;
              this.recursionExpendSuggestionTreeNode(ele.children, roleUnitCode, roleId);
            });
          }
        }
      } else {
        //关闭非节点
        ele.expanded = false;
      }
    })
  }
}
